package com.teach.controller;

import com.teach.pojo.RespBean;
import com.teach.pojo.User;
import com.teach.pojo.req.LoginReq;
import com.teach.pojo.req.PassReq;
import com.teach.service.ClassService;
import com.teach.service.RoleService;
import com.teach.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {
    @Autowired
    private RoleService roleService;
    @Autowired
    private UserService userService;
    @Autowired
    private ClassService classService;


    @GetMapping("/getRoles")
    public RespBean getRoles(){
        return RespBean.success(roleService.list());
    }

    @PostMapping("/login")
    public RespBean login(@RequestBody LoginReq req) {
        return userService.login(req);
    }


    @PostMapping("/updatePass")
    public RespBean updatePass(@RequestBody PassReq req) {
        User user = userService.getById(req.getUserId());

        if (!user.getPassword().equals(req.getOldPass())) {
            return RespBean.fail("密码错误");
        }

        if (user.getPassword().equals(req.getNewPass())) {
            return RespBean.fail("新旧密码一样");
        }

        user.setPassword(req.getNewPass());
        userService.updateById(user);

        return RespBean.success("修改成功");
    }

    @GetMapping("/getStudents")
    public RespBean getStudents(Long classId){
        return RespBean.success(userService.getStudents(classId));
    }

    @GetMapping("/getStudentsAdmin")
    public RespBean getStudents(){
        return RespBean.success(userService.getStudents());
    }

    @GetMapping("/getTeacher")
    public RespBean getTeachers(){
        return RespBean.success(userService.getTeachers());
    }

    @PostMapping("/updateUser")
    public RespBean updateUser(@RequestBody User user) {
        User byId = userService.getById(user.getId());
        byId.setAccount(user.getAccount());
        byId.setName(user.getName());
        userService.updateById(byId);
        return RespBean.success("修改成功");
    }
}
